// packageB/pages/Receipt_code/Receipt_code.js
let drawQrcode = require('../../../utils/wxapp.qrcode.min');//引入wxapp.qrcode.min.js文件
import { ml_hideLoading, ml_showLoading, ml_Toast } from '../../../utils/asyncWX';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userinfo: null,
    if_first: false,
    shareImg: null,
    placeholder: '',
    from_list: {
      login_name: '',
      login_phone: ''
    }
  },
  //获取手机号
  getphone(e) {
    wx.cloud.callFunction({
      name: 'daisho_list', data: {
        type: 'get_phone',
        cloudID: e.detail.cloudID
      }
    }).then(res => {
      var login_phone = res.result.list[0].data.phoneNumber;
      this.setData({ 'from_list.login_phone': login_phone });
      console.log(res);
    })
  },



  createQRcode(canvasWidth, canvasHeight, canvasId, url) {
    // 调用qrcode.js里的方法，传入对应参数
    drawQrcode({
      width: canvasWidth,
      height: canvasHeight,
      canvasId: canvasId,
      text: url
    })
  },
  setCanvasSize() {
    let size = {};
    // getSystemInfoSync  微信小程序提供getSystemInfoSync获取设备的信息
    let res = wx.getSystemInfoSync();
    // console.log(res);
    // 获取比例
    let scale = 600 / 750;
    let width = res.windowWidth * scale;
    let height = width;
    size.w = width;
    size.h = height;
    return size;
  },

  saver_image() {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvars',
      success: function (res) {
        console.log(res)
        that.downloadImg(res.tempFilePath);
      },
      fail: function (res) {
        wx.showToast({ title: '图片生成失败', icon: 'none' });
        console.log("图片生成失败error", res)
      }
    }, this)
  },

  downloadImg: function (url) {　　　　　　　　　　　　　　　　//触发函数
    //成功后的回调函数
    wx.saveImageToPhotosAlbum({　　　　　　　　　//保存到本地
      filePath: url,
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.openSetting({
            success(settingdata) {
              console.log(settingdata)
              if (settingdata.authSetting['scope.writePhotosAlbum']) {
                console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
              } else {
                console.log('获取权限失败，给出不给权限就无法正常使用的提示')
              }
            }
          })
        }
      }
    })
  },



  //加密openid
  password_openid() {
    let openid = wx.getStorageSync('openid');
    console.log(openid)
    let openidlist = openid.split('');
    let openid_ji = []; let openid_or = [];
    for (let i = 0; i < openidlist.length; i++) {
      if (i % 2 == 0) { openid_or.push(openidlist[i]); }
      else { openid_ji.push(openidlist[i]); }
    }; openid_ji = openid_ji.reverse(); openid_or = openid_or.reverse();
    let over_openid = []
    for (let i in openid_or) { over_openid.push(openid_ji[i]); over_openid.push(openid_or[i]); }
    //前14位为奇数，后14位为偶数
    console.log('奇   ' + openid_ji)
    console.log('偶   ' + openid_or)

    let passwoord_openid = openid_ji.join('') + over_openid.join('') + openid_or.join('');
    console.log(passwoord_openid);
    //前面10位与后面10为随机数字 ,保证每次进去二维码都不一样。
    let tem1 = parseInt(Math.random() * (13 - 4 + 1) + 4, 10);
    let tem2 = parseInt(Math.random() * (13 - 4 + 1) + 4, 10);
    let number1 = passwoord_openid.substring(tem1, tem1 + 10);
    let number2 = passwoord_openid.substring(tem2, tem2 + 10);
    console.log(number1 + passwoord_openid + number2);
    return number1 + passwoord_openid + number2;
  },

  //获取用户数据
  getUserProfile(e) {
    wx.getUserProfile({
      lang: 'zh_CN',
      desc: '用于完善个人资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        wx.setStorageSync('userinfo', res.userInfo);
        this.setData({
          userinfo: res.userInfo
        })
      }
    })
  },


  getcode() {
    let openid = wx.getStorageSync('openid');
    let userinfo = wx.getStorageSync('userinfo');
    this.setData({ userinfo: userinfo });
    var that = this;
    //判断用户是否注册
    ml_showLoading();
    wx.cloud.callFunction({
      name: 'daisho_list', data: {
        type: 'get_code',
        openid: openid,
      }
    }).then(res => {
      console.log(res)
      ml_hideLoading();
      if (res.result.data.length != 0) {
        wx.setStorageSync('userinfo_inf', res.result.data[0]);
        that.setData({ userinfo_inf: res.result.data[0], if_first: true });
      }
    })
  },
  
  login_name(e) {
    this.setData({ 'from_list.login_name': e.detail.value });
  },
  tip_counp(){
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '新用户可以领取下面的新人优惠卷，最高可体验1分钱下单。',
      cancelText:'取消',
      confirmText:'已领取',
      success (res) {
        if (res.confirm) {
          that.create_code();
        } 
      }
    })
  },

  //生成二维码
  create_code() {
    let openid = wx.getStorageSync('openid');
    if (this.data.from_list.login_name == '') { ml_Toast('请填写姓名！'); return; };
    if (this.data.from_list.login_phone == '') { ml_Toast('请获取手机号码！'); return; };
    let from_list = {
      login_name: this.data.from_list.login_name,
      login_phone: this.data.from_list.login_phone,
      login_openid: openid,
      login_inf: wx.getStorageSync('userinfo'),
      login_sincerity: 100
    }
    console.log(from_list);
    wx.cloud.callFunction({
      name: 'daisho_list', data: {
        type: 'up_code',
        openid: openid,
        datas: from_list
      }
    }).then(res => {
      if (res.result.code == 200) {
        wx.showToast({
          title: '生成成功',
        })
        this.getcode();
      }
    })
  },

  givecoupom(){
    //随机字符串 三个统一即可  
    let give_String = Math.random().toString(36).substr(2, 15) + Math.random().toString(36).substr(2, 15);
    // 全局存储
    app.globalData.give_String = give_String;
    // 内存存储、
    wx.setStorageSync('give_String', give_String);
    wx.navigateTo({
      url: '/packageB/pages/page_coupon/page_coupon?give_String='+give_String,
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    let userinfo_inf = wx.getStorageSync('userinfo_inf');
    if (userinfo_inf == '') {this.getcode();}
    else{this.setData({userinfo_inf:userinfo_inf,if_first: true})}

    this.setData({ placeholder: this.password_openid() });
    //setCanvasSize  拿到画布区域的尺寸（微信小程序不支持dom的操作，所以单独定义方法去获取）
    let size = this.setCanvasSize();
    // console.log(size);
    let url = this.data.placeholder;
    //调用createQRcode方法
    this.createQRcode(size.w, size.h, 'mycanvars', url);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})